import enum
import logging

from selenium.webdriver.chrome.webdriver import WebDriver as ChromeDriver
from selenium.webdriver.firefox.webdriver import WebDriver as FirefoxDriver
from selenium.webdriver.edge.webdriver import WebDriver as EdgeDriver
from selenium.webdriver.chromium.options import ChromiumOptions
from fromework.config.settings import WEB_DRIVER_PATH, DEFAULT_TIMEOUT
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver

logger = logging.getLogger(__name__)


class BrowserType(enum.Enum):
    Chrome = 1
    FIREFOX = 2
    EDGE = 3


class WebDriverFactory:
    __instance: RemoteWebDriver = None

    @classmethod
    def get_instance(cls, browser_type: BrowserType = BrowserType.Chrome, enable_headless=False):
        if not cls.__instance:
            option = ChromiumOptions()
            # 使用headless无界面浏览器模式
            if enable_headless:
                option.add_argument('--headless')
                option.add_argument('--disable-gpu')
            # 设置驱动路径
            option.binary_location = WEB_DRIVER_PATH
            # 设置浏览器类型
            if browser_type == BrowserType.Chrome:
                cls.__instance = ChromeDriver()
            elif browser_type == BrowserType.FIREFOX:
                cls.__instance = FirefoxDriver()
            elif browser_type == BrowserType.EDGE:
                cls.__instance = EdgeDriver()
            cls.__instance.maximize_window()
            cls.__instance.implicitly_wait(DEFAULT_TIMEOUT)
        logger.info("driver initialization successfully!")
        return cls.__instance

    @classmethod
    def stop(cls):
        if cls.__instance:
            cls.__instance.quit()
            cls.__instance = None
        logger.info("driver has been stop.")

